package io.rong.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.yunshipei.EnterApplication;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.ui.dialog.CreateGroupDialog;
import com.yunshipei.utils.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.app.activity.LocationMapActivity;
import io.rong.app.common.DemoApi;
import io.rong.app.database.DBManager;
import io.rong.app.database.UserInfos;
import io.rong.app.database.UserInfosDao;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.model.IFilterModel;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

/**
 * Created by Bob on 2015/1/30.
 */
public class DemoContext {

    private volatile static DemoContext mDemoContext;
    public Context mContext;
    private DemoApi mDemoApi;
    private Map<String, Group> groupMap;
    private ArrayList<UserInfo> mUserInfos;
    private ArrayList<UserInfo> mFriendInfos;
    private SharedPreferences mPreferences;
    private RongIM.LocationProvider.LocationCallback mLastLocationCallback;
    private UserInfosDao mUserInfosDao;
    private UserInfo currentUserInfo;
    public static final int STATE1 = 1;
    public static final int STATE2 = 2;
    public static final int STATE3 = 3;
    private DatabaseUtil databaseUtil = null;

    /**
     * 群组信息
     */
    private List<GroupCreateInfo> result;

    public static DemoContext getInstance(Context context) {
        if (mDemoContext == null)
            synchronized (DemoContext.class) {
                if (mDemoContext == null) {
                    mDemoContext = new DemoContext(context);
                }
            }
        return mDemoContext;
    }

    public static DemoContext getInstance() {
        if (mDemoContext == null)
            mDemoContext = new DemoContext();
        return mDemoContext;
    }

    private DemoContext() {
        result = new ArrayList<GroupCreateInfo>();
        groupMap = new HashMap<>();
    }

    private DemoContext(Context context) {
        mContext = context;
        mDemoContext = this;
        databaseUtil = new DatabaseUtil();
        result = new ArrayList<GroupCreateInfo>();
        //http初始化 用于登录、注册使用
        mPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        RongIM.setLocationProvider(new LocationProvider());

        mDemoApi = new DemoApi(context);

        mUserInfosDao = DBManager.getInstance(mContext).getDaoSession().getUserInfosDao();
    }

    public static void init(Context context) {
        mDemoContext = new DemoContext(context);
    }

    public SharedPreferences getSharedPreferences() {
        return mPreferences;
    }

    public void setSharedPreferences(SharedPreferences sharedPreferences) {
        this.mPreferences = sharedPreferences;
    }

    public void setGroupMap(Map<String, Group> groupMap) {
        this.groupMap = groupMap;
    }

    //新建群组添加其中
    public void addInfoGroupMap(Map<String, Group> map) {
        if (groupMap == null)
            groupMap = new HashMap<>();
        groupMap.putAll(map);
    }

    public Map<String, Group> getGroupMap() {
        List<GroupCreateInfo> list = getResult();
        if (groupMap == null)
            groupMap = new HashMap<>();
        Group group = null;
        for (int i = 0; list != null && i < list.size(); i++) {
            if (!TextUtils.isEmpty(list.get(i).getId()) && !TextUtils.isEmpty(list.get(i).getName())) {
                group = new Group(list.get(i).getId(), list.get(i).getName(), Uri.parse(list.get(i).getPortraitUri()));
                groupMap.put(group.getId(), group);
            }
        }
        return groupMap;
    }


    public ArrayList<UserInfo> getUserInfos() {
        return mUserInfos;
    }

    public void setUserInfos(ArrayList<UserInfo> userInfos) {
        mUserInfos = userInfos;
    }

    //添加新创建的群组
    public void addGroupCreateInfo(GroupCreateInfo newGroupList) {
        this.result.add(newGroupList);
    }

    /**
     * 当state=1时修改的是头像想uri
     * 当state=2时修改的是群名称
     *
     * @param id
     * @param avatarUri
     * @param state
     */
    public synchronized void updateGroupInfoById(String id, String avatarUri, int state) {
        if (state != STATE3)
            for (Map.Entry<String, Group> entry : groupMap.entrySet()) {
                if (entry.getKey().equals(id)) {
                    if (state == STATE1)
                        entry.getValue().setPortraitUri(Uri.parse(avatarUri));
                    else if (state == STATE2)
                        entry.getValue().setName(avatarUri);
                } else {
                }
            }
        for (int i = 0; i < this.result.size(); i++) {
            if (this.result.get(i).getId().equals(id)) {
                if (state == STATE1)
                    this.result.get(i).setPortraitUri(avatarUri);
                else if (state == STATE2)
                    this.result.get(i).setName(avatarUri);
                else if (state == STATE3)
                    this.result.get(i).setNumber(Integer.parseInt(avatarUri));
                if (databaseUtil != null)
                    databaseUtil.updateGroup(result.get(i));
                break;
            } else {
            }
        }
    }

    public synchronized void updateGroupInfoById(String id, String newGroupMembers) {
        for (int i = 0; i < this.result.size(); i++) {
            if (this.result.get(i).getId().equals(id)) {
                this.result.get(i).setGourpMembers(newGroupMembers);
//                DatabaseUtil dbUtil = new DatabaseUtil(EnterApplication.getApp().getApplicationContext());
                if (databaseUtil != null)
                    databaseUtil.updateGroup(result.get(i));
                break;
            } else {
            }
        }
    }

    public void updateGroupInfoById(String id, GroupCreateInfo groupCreateInfo) {
        for (int i = 0; i < this.result.size(); i++) {
            if (this.result.get(i).getId().equals(id)) {
                this.result.get(i).setGourpMembers(groupCreateInfo.getGourpMembers());
//                DatabaseUtil dbUtil = new DatabaseUtil(EnterApplication.getApp().getApplicationContext());
                if (databaseUtil != null)
                    databaseUtil.updateGroup(groupCreateInfo);
                break;
            } else {
//                DatabaseUtil dbUtil = new DatabaseUtil(EnterApplication.getApp().getApplicationContext());
                if (databaseUtil != null)
                    databaseUtil.updateOrInsertGroups(groupCreateInfo);   //升级或更新
            }
        }
    }


    public void setResult(List<GroupCreateInfo> gcinfo) {
        this.result = gcinfo;
    }

    public void removeOneFromResult(GroupCreateInfo grCInfo) {
        this.result.remove(grCInfo);
    }

    public List<GroupCreateInfo> getResult() {
        if (result != null && result.size() <= 0) {
            result = databaseUtil.queryGroups();
        }
        return result;
    }

    public GroupCreateInfo getOneResult(String groupId) {
        GroupCreateInfo newGroupCreateInfo = null;
        if (!StringUtil.isEmpty(groupId)) {
            for (int i = 0; i < result.size(); i++) {
                if (groupId.equals(result.get(i).getId())) {
                    newGroupCreateInfo = result.get(i);
                    break;
                }
            }
            if (newGroupCreateInfo == null) {
//                DatabaseUtil dbUtil = new DatabaseUtil(EnterApplication.getApp().getApplicationContext());
                if (databaseUtil != null)
                    newGroupCreateInfo = databaseUtil.findGroupById(groupId);
                Log.d("Demo Context", "从数据库获取信息");
            }
        } else {
            Log.e("DemoContext", "groupId is null");
        }
        return newGroupCreateInfo;
    }


    public DemoApi getDemoApi() {
        return mDemoApi;
    }

    /**
     * 删除 userinfos 表
     */
    public void deleteUserInfos() {

        mUserInfosDao.deleteAll();
    }

    /**
     * 更新 好友信息
     *
     * @param targetid
     * @param status
     */
    public void updateUserInfos(String targetid, String status) {

        UserInfos userInfos = mUserInfosDao.queryBuilder().where(UserInfosDao.Properties.Userid.eq(targetid)).unique();
        userInfos.setStatus(status);
        userInfos.setUsername(userInfos.getUsername());
        userInfos.setPortrait(userInfos.getPortrait());
        userInfos.setUserid(userInfos.getUserid());

        mUserInfosDao.update(userInfos);

    }

    /**
     * 向数据库插入数据
     *
     * @param info   用户信息
     * @param status 状态
     */
    public void insertOrReplaceUserInfo(UserInfo info, String status) {

        UserInfos userInfos = new UserInfos();
        userInfos.setStatus(status);
        userInfos.setUsername(info.getName());
        userInfos.setPortrait(String.valueOf(info.getPortraitUri()));
        userInfos.setUserid(info.getUserId());
        mUserInfosDao.insertOrReplace(userInfos);
    }

    /**
     * 通过userid 查找 UserInfo，查找的是本地的数据库
     *
     * @param userId
     * @return
     */
    public UserInfo getUserInfoById(String userId) {

        UserInfos userInfos = mUserInfosDao.queryBuilder().where(UserInfosDao.Properties.Userid.eq(userId)).unique();

        if (userInfos == null)
            return null;

        return new UserInfo(userInfos.getUserid(), userInfos.getUsername(), Uri.parse(userInfos.getPortrait()));
    }

    /**
     * 获得好友列表
     *
     * @return
     */
    public ArrayList<UserInfo> getFriendList() {
        List<UserInfo> userInfoList = new ArrayList<UserInfo>();

        List<UserInfos> userInfos = mUserInfosDao.queryBuilder().where(UserInfosDao.Properties.Status.eq("5")).list();

        if (userInfos == null)
            return null;

        for (int i = 0; i < userInfos.size(); i++) {
            UserInfo userInfo = new UserInfo(userInfos.get(i).getUserid(), userInfos.get(i).getUsername(), Uri.parse(userInfos.get(i).getPortrait()));

            userInfoList.add(userInfo);
        }
        return (ArrayList) userInfoList;
    }

    /**
     * 根据userids获得好友列表
     *
     * @return
     */
    public ArrayList<UserInfo> getUserInfoList(String[] userIds) {

        List<UserInfo> userInfoList = new ArrayList<UserInfo>();
        List<UserInfos> userInfosList = new ArrayList<UserInfos>();

        for (int i = 0; i < userIds.length; i++) {
            UserInfos userInfos = mUserInfosDao.queryBuilder().where(UserInfosDao.Properties.Userid.eq(userIds[i])).unique();
            userInfosList.add(userInfos);
            UserInfo userInfo = new UserInfo(userInfosList.get(i).getUserid(), userInfosList.get(i).getUsername(), Uri.parse(userInfosList.get(i).getPortrait()));
            userInfoList.add(userInfo);
        }

        if (userInfosList == null)
            return null;


        return (ArrayList) userInfoList;
    }

    /**
     * 通过groupid 获得groupname
     *
     * @param groupid
     * @return
     */
    public String getGroupNameById(String groupid) {
        Log.e("getGroupNameById", "********** ----- get Group Name By ID");
        Group groupReturn = null;
        if (!TextUtils.isEmpty(groupid) && groupMap != null) {

            if (groupMap.containsKey(groupid)) {
                groupReturn = groupMap.get(groupid);
            } else
                return null;

        }
        if (groupReturn != null)
            return groupReturn.getName();
        else
            return null;
    }


    public RongIM.LocationProvider.LocationCallback getLastLocationCallback() {
        return mLastLocationCallback;
    }

    public void setLastLocationCallback(RongIM.LocationProvider.LocationCallback lastLocationCallback) {
        this.mLastLocationCallback = lastLocationCallback;
    }

    class LocationProvider implements RongIM.LocationProvider {

        /**
         * 位置信息提供者:LocationProvider 的回调方法，打开第三方地图页面。
         *
         * @param context  上下文
         * @param callback 回调
         */
        @Override
        public void onStartLocation(Context context, RongIM.LocationProvider.LocationCallback callback) {
            /**
             * demo 代码  开发者需替换成自己的代码。
             */
//            DemoContext.getInstance(context).setLastLocationCallback(callback);
//            Intent intent = new Intent(context, LocationMapActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(intent);//SOSO地图
        }
    }

    public boolean hasUserId(String userId) {
        if (userId != null) {
            UserInfos userInfos = mUserInfosDao.queryBuilder().where(UserInfosDao.Properties.Userid.eq(userId)).unique();
            if (userInfos == null) {
                return false;
            }
        }
        return true;
    }

    public UserInfo getCurrentUserInfo() {
        return currentUserInfo;
    }

    public void setCurrentUserInfo(UserInfo currentUserInfo) {
        this.currentUserInfo = currentUserInfo;
    }

}
